#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
拦截代理API路由
"""

import logging
from flask import Blueprint, request, Response
from intercept.services.intercept_service import InterceptService

logger = logging.getLogger(__name__)

# 创建蓝图
proxy_bp = Blueprint('proxy', __name__)

@proxy_bp.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def proxy(path):
    """代理请求"""
    try:
        # 获取请求信息
        method = request.method
        url = request.args.get('url')
        if not url:
            url = f"http://{path}"
        
        headers = {key: value for key, value in request.headers if key != 'Host'}
        body = request.get_data()
        
        # 获取服务名称
        service_name = request.headers.get('X-Service-Name')
        if not service_name:
            # 如果没有指定服务名称，尝试从URL中提取
            service_name = url.split('://')[1].split('/')[0] if '://' in url else url.split('/')[0]
            service_name = service_name.split(':')[0]  # 移除端口号
        
        # 拦截请求
        intercepted, status_code, headers, body, record_id = InterceptService.intercept_request(
            service_name, method, url, headers, body
        )
        
        # 构建响应
        if intercepted:
            # 添加拦截标记
            headers['X-Intercepted'] = 'true'
        
        return Response(
            body,
            status=status_code,
            headers=headers
        )
    
    except Exception as e:
        logger.error(f"代理请求失败: {e}")
        return Response(
            f"代理请求失败: {str(e)}",
            status=500,
            headers={"Content-Type": "text/plain"}
        )
